package com.example.remotecontrol.ui.devices

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.DeviceType
import com.example.remotecontrol.data.repository.DeviceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 设备管理界面的ViewModel
 */
@HiltViewModel
class DevicesViewModel @Inject constructor(
    private val deviceRepository: DeviceRepository
) : ViewModel() {

    // 当前设备查看模式
    private val _viewMode = MutableStateFlow(DeviceViewMode.ALL)
    val viewMode: StateFlow<DeviceViewMode> = _viewMode.asStateFlow()
    
    // 设备搜索关键词
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()
    
    // 所有设备列表
    val allDevices = deviceRepository.devices.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 收藏设备列表
    val favoriteDevices = deviceRepository.favoriteDevices.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 最近使用设备列表
    val recentDevices = deviceRepository.recentDevices.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 按类型分组的设备列表
    val devicesByType = deviceRepository.devicesByType.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyMap()
    )
    
    // 按房间分组的设备列表
    val devicesByRoom = deviceRepository.devicesByRoom.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyMap()
    )
    
    // 根据当前视图模式和搜索查询过滤后的设备列表
    val filteredDevices: StateFlow<List<Device>> = combine(
        allDevices,
        favoriteDevices,
        recentDevices,
        viewMode,
        searchQuery
    ) { all, favorites, recent, mode, query ->
        val baseList = when (mode) {
            DeviceViewMode.ALL -> all
            DeviceViewMode.FAVORITES -> favorites
            DeviceViewMode.RECENT -> recent.take(5) // 只显示最近5个设备
        }
        
        if (query.isBlank()) {
            baseList
        } else {
            baseList.filter { device ->
                device.name.contains(query, ignoreCase = true) ||
                device.brand.contains(query, ignoreCase = true) ||
                device.model.contains(query, ignoreCase = true) ||
                device.room.contains(query, ignoreCase = true) ||
                device.type.displayName.contains(query, ignoreCase = true)
            }
        }
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    /**
     * 获取指定类型的设备数量
     */
    fun getDeviceCountByType(type: DeviceType): Flow<Int> {
        return allDevices.map { devices ->
            devices.count { it.type == type }
        }
    }
    
    /**
     * 设置设备查看模式
     */
    fun setViewMode(mode: DeviceViewMode) {
        _viewMode.value = mode
    }
    
    /**
     * 设置搜索查询关键词
     */
    fun setSearchQuery(query: String) {
        _searchQuery.value = query
    }
    
    /**
     * 添加或更新设备
     */
    fun addOrUpdateDevice(device: Device) {
        viewModelScope.launch {
            deviceRepository.addOrUpdateDevice(device)
        }
    }
    
    /**
     * 删除设备
     */
    fun deleteDevice(deviceId: String) {
        viewModelScope.launch {
            deviceRepository.deleteDevice(deviceId)
        }
    }
    
    /**
     * 切换设备收藏状态
     */
    fun toggleFavorite(deviceId: String) {
        viewModelScope.launch {
            val device = deviceRepository.getDeviceById(deviceId)
            device?.let {
                deviceRepository.setDeviceFavorite(deviceId, !it.isFavorite)
            }
        }
    }
    
    /**
     * 更新设备使用时间
     */
    fun updateDeviceUsage(deviceId: String) {
        viewModelScope.launch {
            deviceRepository.updateDeviceLastUsed(deviceId)
        }
    }
    
    /**
     * 获取指定ID的设备
     */
    suspend fun getDeviceById(deviceId: String): Device? {
        return deviceRepository.getDeviceById(deviceId)
    }
    
    /**
     * 创建示例设备数据（用于初始化演示）
     */
    fun createSampleDevices() {
        viewModelScope.launch {
            deviceRepository.createSampleDevices()
        }
    }
}

/**
 * 设备查看模式枚举
 */
enum class DeviceViewMode {
    ALL,        // 所有设备
    FAVORITES,  // 收藏设备
    RECENT      // 最近使用
} 